package com.lanou.renrenxin.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.easemob.chat.EMGroupManager;
import com.easemob.exceptions.EaseMobException;
import com.lanou.renrenxin.R;
import com.lanou.renrenxin.adapter.SortAdapter;
import com.lanou.renrenxin.base.BaseActivity;
import com.lanou.renrenxin.base.BaseApplication;
import com.lanou.renrenxin.custommodule.SideBar;
import com.lanou.renrenxin.shortlistview.CharacterParser;
import com.lanou.renrenxin.shortlistview.PinyinComparator;
import com.lanou.renrenxin.shortlistview.SortModel;
import com.lanou.renrenxin.thread.GetUserNameThread;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by zy on 16/3/10.
 * 选取加入群组成员界面
 */
public class PickGroupContactActivity extends BaseActivity implements AdapterView.OnItemClickListener, View.OnClickListener {
    private ListView listView;
    private SideBar sideBar;
    private TextView dialog, textViewTitle;
    private SortAdapter sortAdapter;
    private List<String> contactnames;
    private CharacterParser characterParser;
    private List<SortModel> sourceDateList;
    private PinyinComparator pinyinComparator;
    private Handler handler;
    private Button btnSave, btnBack;
    //要加到群组的人的集合
    private ArrayList<String> groupMembers;
    //群组名称,群组介绍
    private String groupName, groupIntroduce;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pickgroupcontact);
        //初始化
        groupMembers = new ArrayList<>();
        initView();
        setUp();
    }

    private void initView() {
        characterParser = characterParser.getInstance();
        pinyinComparator = new PinyinComparator();
        sideBar = (SideBar) findViewById(R.id.pickgroupcontact_sidrbar);
        dialog = (TextView) findViewById(R.id.dialog_pick);
        listView = (ListView) findViewById(R.id.pickgroupcontact_listview);
        btnSave = (Button) findViewById(R.id.btnCreat);
        btnBack = (Button) findViewById(R.id.btnBack);
        textViewTitle = (TextView) findViewById(R.id.txtTitle);
    }

    private void setUp() {
        sideBar.setTextView(dialog);
        btnSave.setVisibility(View.VISIBLE);
        btnBack.setVisibility(View.VISIBLE);
        btnBack.setOnClickListener(this);
        btnSave.setOnClickListener(this);
        textViewTitle.setText("选取群组成员");
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                int position = sortAdapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    listView.setSelection(position);
                }
            }
        });
        //子线程操作, 获取联系人
        handler = new android.os.Handler(new android.os.Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (msg.what == 100) {
                    contactnames = (List<String>) msg.obj;
                    sourceDateList = filledData(contactnames);
                    Collections.sort(sourceDateList, pinyinComparator);
                    sortAdapter = new SortAdapter(BaseApplication.getContext(), sourceDateList);
                    listView.setAdapter(sortAdapter);
                }
                return false;
            }
        });
        new GetUserNameThread(handler).start();
        listView.setOnItemClickListener(this);
        Intent intent = this.getIntent();
        groupName = intent.getStringExtra("groupname");
        groupIntroduce = intent.getStringExtra("groupintroduce");

    }


    //首字母
    private List<SortModel> filledData(List<String> date) {
        List<SortModel> mSortList = new ArrayList<SortModel>();
        for (int i = 0; i < date.size(); i++) {
            SortModel sortModel = new SortModel();
            sortModel.setName(date.get(i));

            String pinyin = characterParser.getSelling(date.get(i));
            String sortString = pinyin.substring(0, 1).toUpperCase();

            //
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("#");
            }

            mSortList.add(sortModel);
        }
        return mSortList;
    }


    //listview点击事件,获取选中的联系人
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        if (groupMembers.indexOf(sourceDateList.get(position).getName()) != -1) {
            groupMembers.remove(sourceDateList.get(position).getName());
            view.setBackgroundResource(R.color.color_transprent);
        } else {
            String name = sourceDateList.get(position).getName();
            groupMembers.add(name);
            view.setBackgroundResource(R.color.renrenxin_color_blue);
        }

    }

    //button点击监听
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnBack:
                finish();
                break;
            case R.id.btnCreat:
                //创建公开群组,list转为String
                final String[] member = groupMembers.toArray(new String[groupMembers.size()]);

                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        try {
                            EMGroupManager.getInstance().createPrivateGroup(groupName, groupIntroduce, member, true);

                        } catch (EaseMobException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();

                BaseActivity.ShowToast("注册群组成功");
                //广播通知群组列表更新
                Intent intent = new Intent();
                intent.setAction("action.refreshGroup");
                sendBroadcast(intent);
                finish();
                break;
        }
    }

}
